import React from 'react';
import './style.css';
import {Input, Button, Alert} from 'antd';
import r from './request'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import {login} from '../../../actions/auth'

class LoginPage extends React.Component {

    state ={
        username: '', password: '', pendingState: false,
        alert: {
            display: false,
            message: ''
        },
        current: 'login',
    };

    handleOnTextChange = (e) =>{
        const state = this.state;
        state[e.target.name] = e.target.value;
        this.setState(state);
    };

    handleOnLoginBtnClick = () => {
        const state = this.state;
        const {username, password} = state;
        if(!username || !password){
            state.alert.display = true;
            state.alert.message = "账号或密码不能为空";
            this.setState(state);
            return;
        }
        r('/login', {username, password})
            .then(res => {
                state.pendingState = false;
                const {status, token, data} = res;
                if(!status){
                    state.alert.display = true;
                    state.alert.message = "账号或密码不正确";
                    this.setState(state);
                }else{
                    this.props.login({user: data, token});
                    this.props.history.push('/index')
                }
            })
    };

    renderAlert = () => {
        if(this.state.alert.display){
            return (
                <Alert className='wrapperControl' message={this.state.alert.message} type="error" showIcon/>
            )
        }else{
            return null;
        }
    };

    render(){
        return(
            <div className='loginPage'>
                <div className='wrapperControl'>
                    <h2 className='wrapperControl'>登录</h2>
                    {this.renderAlert()}
                    <Input type={'text'} className='wrapperControl' name={'username'} onChange={this.handleOnTextChange} size={'large'} value={this.state.username} placeholder={'请输入用户名'} />
                    <Input type={'password'} className='wrapperControl' name={'password'} onChange={this.handleOnTextChange} size={'large'} value={this.state.password} placeholder={'请输入密码'} />
                    <Button className='btnLogin' type={'primary'} size={'large'} disabled={this.state.pendingState} onClick={this.handleOnLoginBtnClick}>提交</Button>
                </div>
            </div>
        )
    }

}


const mapStateToProps = ({auth}) =>({auth});
const mapDispatchToProps = (dispatch) => (bindActionCreators({login}, dispatch));

export default connect(mapStateToProps, mapDispatchToProps)(LoginPage);
